package com.wave.gate.controller;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson2.JSON;
import com.wave.gate.enums.RedisKeyEnum;
import com.wave.gate.init.InitBaseInfo;
import com.wave.gate.mqtt.client.MqttSendClient;
import com.wave.gate.util.*;
import com.wave.gate.vo.AiAlarmVO;
import com.wave.gate.vo.GatePassSetVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.net.*;
import java.util.Date;

import static com.wave.gate.util.GuavaCache.*;

/**
 * @author linhui
 * @date 2023/5/8 16:31
 * @version: 1.0
 */
@Slf4j
@RestController
@RequestMapping("/aiAlarm")
public class AiAlarmController {


    @Autowired
    private MqttSendClient mqttSendClient;

    //A门闸机端口
    public int gateAPort = 502;

    //B门闸机端口
    public int gateBPort = 502;

    /**
     * 01：常关；12：进向禁止、出向自由
     */
    private final String doorCommand = "000000000006010600410112";

    /**
     * 01：常关；22：进向禁止、出向禁止
     */
    private final String doorCommand2 = "000000000006010600410122";

    /**
     * 接收AI告警记录
     */
    @PostMapping("/accept")
    public void add(@RequestBody AiAlarmVO aiAlarmVO, HttpServletRequest request) throws InterruptedException, IOException {

        String modelPath = InitBaseInfo.modelPathMap.get(aiAlarmVO.getModelPath());
        String roiType = InitBaseInfo.roiTypeMap.get(aiAlarmVO.getRoiType());

        log.info("接受到AI告警转发记录modelPath:{}, deviceIp:{} ,roiType:{} ,roiId:{}, 时间：{}",
                aiAlarmVO.getModelPath() + "-" + modelPath, aiAlarmVO.getDeviceIp(), roiType, aiAlarmVO.getRoiId(), DateUtil.date(Long.parseLong(aiAlarmVO.getTime())));

        if ("危险区域闯入".equals(modelPath)) {
            AI_WX_CACHE.put(RedisKeyEnum.KEY_AI_ALARM.getCode(), modelPath);
            return;
        }
        //去重，5秒内的告警算同一个，只保留一次
        String checkModelPathKey = modelPath + ":" + aiAlarmVO.getRoiId() + ":" + DateUtil.format(new Date(),"yyyy-MM-dd HH:mm");
        log.info("CHECK_MODELPATH_CACHE:{}",CHECK_MODELPATH_CACHE.getIfPresent(checkModelPathKey));
        if(CHECK_MODELPATH_CACHE.getIfPresent(checkModelPathKey)==null){
            log.info("插入AI告警");
            CHECK_MODELPATH_CACHE.put(checkModelPathKey, modelPath);

            String key = "";
            GatePassSetVo gatePassSetVo = GuavaCache.PASSSET_CACHE.getIfPresent("passsetipInfo");
            if ("跨越".equals(modelPath)) {
                Socket doorA = null;
                Socket doorB = null;
                try {
                    VoicePlayerUtil.voicePlay(6);
                    String gateAIp = gatePassSetVo.getInGateIp();//A门闸机IP
                    String gateBIp = gatePassSetVo.getOutGateIp();//B门闸机IP
                    doorA = new Socket(gateAIp, gateAPort);
                    doorB = new Socket(gateBIp, gateBPort);
                    SocketClientUtil.sendData(doorA, doorCommand2);
                    SocketClientUtil.sendData(doorB, doorCommand2);
                }finally {
                    if (doorA != null) {
                        doorA.close();
                    }
                    if (doorB != null) {
                        doorB.close();
                    }
                }
            }

            if ("已穿访客工衣".equals(modelPath)) {
                String camera = "入口";
                String deviceIp = aiAlarmVO.getDeviceIp();
                if(deviceIp.contains(gatePassSetVo.getOutCameraIp())){
                    camera = "出口";
                }
                key = RedisKeyEnum.KEY_AI_GY.getCode() + ":" + camera;
                log.info("已穿访客工衣key={}", key);
            } else {
                key = RedisKeyEnum.KEY_AI_ALARM.getCode();
            }
            AI_CACHE.put(key, modelPath);
            //把图片base64位放到redis供 有人通行时，添加记录用
            String imgKey = RedisKeyEnum.KEY_AI_ALARM.getCode() + ":IMG";
            AI_CACHE.put(imgKey, aiAlarmVO.getEmergencyImageBase64());

            if ("尾随".equals(modelPath)) {

                String camera = "入口";
                String deviceIp = aiAlarmVO.getDeviceIp();
                if(deviceIp.contains(gatePassSetVo.getOutCameraIp())||
                        deviceIp.contains(gatePassSetVo.getOutMiddleCameraIp())){
                    camera = "出口";
                }

                log.info("================================尾随：{}", modelPath + "-" + camera + "-" + roiType);

                //如果没有人进去，就直接播放语音
                if(HASHUMAN_CACHE.getIfPresent("hasHuman")==null){
                    VoicePlayerUtil.voicePlay(18);
                }

                key = RedisKeyEnum.KEY_AI_ALARM.getCode();
                AI_CACHE.put(key, modelPath + "-" + camera + "-" + roiType);

                //如果有人进去，那么打开A门
                String deviceType = DEVICETYPE_CACHE.getIfPresent("deviceType");
                if(StringUtils.isNotEmpty(deviceType) && "门内告警".equals(roiType)){
                    Socket doorA = null;
                    Socket doorB = null;
                    if("in".equals(deviceType)){
                        String gateAIp = gatePassSetVo.getInGateIp();//A门闸机IP
                        String gateBIp = gatePassSetVo.getOutGateIp();//B门闸机IP
                        doorA = new Socket(gateAIp, gateAPort);
                        doorB = new Socket(gateBIp, gateBPort);
                    }else {
                        String gateAIp = gatePassSetVo.getOutGateIp();//A门闸机IP
                        String gateBIp = gatePassSetVo.getInGateIp();//B门闸机IP
                        doorA = new Socket(gateAIp, gateAPort);
                        doorB = new Socket(gateBIp, gateBPort);
                    }
                    try {
                        SocketClientUtil.sendData(doorA, doorCommand);
                        SocketClientUtil.sendData(doorB, doorCommand2);
                    }finally {
                        DEVICETYPE_CACHE.invalidateAll();
                        if (doorA != null) {
                            doorA.close();
                        }
                        if (doorB != null) {
                            doorB.close();
                        }
                    }
                }
            }


            //mqtt发送告警信息给后台管理中心,只保存没有人扫脸的情况
            if(HASHUMAN_CACHE.getIfPresent("hasHuman")==null){
                aiAlarmVO.setModelPath(modelPath);
                aiAlarmVO.setHasHuman(false);
                String sendMessage = JSON.toJSONString(aiAlarmVO);
                mqttSendClient.publish(false, "wave-gate:AA", sendMessage);
            }

        }


    }

}
